package com.cg.controller;

import com.cg.encoder.MyPasswordEncoder;
import com.cg.entity.User;
import com.cg.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserServiceImpl userService;

    @RequestMapping("/login")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/loginFail")
    public String loginFail(){
        return "loginFail";
    }

    @RequestMapping("/main")
    public String main(){
        return "main";
    }

    @RequestMapping("/registerPage")
    public String registerPage(){
        return "register";
    }

    @PostMapping("/register")
    public String register(User user) {
        try {
            // 创建MyPasswordEncoder的实例
            MyPasswordEncoder passwordEncoder = new MyPasswordEncoder();

            // 使用自定义的密码加密器加密密码
            String encodedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encodedPassword); // 设置加密后的密码
            // 调用服务层的方法注册用户
            boolean result = userService.save(user);
            if (result) {
                // 注册成功，重定向到登录页面
                return "redirect:/user/login";
            } else {
                // 注册失败，返回注册页面并提示错误信息
                return "register";
            }
        } catch (Exception e) {
            // 异常处理，返回错误页面或处理逻辑
            e.printStackTrace();
            return "error";
        }
    }


}